package org.jwap.server.net;

import java.util.ArrayList;
import java.util.List;

import org.jwap.server.helper.Enums;
import org.jwap.server.utils.FileCore;


public class ConnectionCore {
	
	public final static String EOF= "\r\n";
	
	public static List<List<String>> mimeTypes = null;
	
	public ConnectionCore(){
		if( mimeTypes == null ){
			initMimes();
		}
	}
	
	private void initMimes(){
		if ( mimeTypes == null ){
			mimeTypes = new ArrayList<List<String>>();
			
			String mimes = FileCore.readTextFile("config/mimes.jwap", false);
			String[] lines = mimes.split("\r\n");
			for ( String line: lines){
				String[] params = line.split(",");
				if ( params.length > 1 ){
					List<String> mime = new ArrayList<>();
					mime.add(params[0].trim());
					mime.add(params[1].trim());
					mimeTypes.add(mime);
				}
			}
		}
	}
	
	public static String getMimeHeader(String path){
		String header = "Content-Type: ";
		if(path.contains(".")){
			String [] pathArray = path.split("\\.");
			if(pathArray.length >= 2){
				for(List<String> mime : mimeTypes){
					if(mime.get(0).equals(pathArray[pathArray.length-1])){
						header = header + pathArray[pathArray.length-1]+"\r\n";
						break;
					}
				}
			}
		}	
		return header;
	}
	
	public static String httpHeader(Enums.HttpStatus status, String path) {
		StringBuilder header = new StringBuilder();
		header.append("HTTP/1.0 ");
		String headerStatus = "501 Not Implemented";
		if(status == Enums.HttpStatus.HTTP200){
			headerStatus = "200 OK";
		}
		else if(status == Enums.HttpStatus.HTTP400){
			headerStatus = "400 Bad Request";
		}
		else if(status == Enums.HttpStatus.HTTP403){
			headerStatus = "403 Forbidden";
		}
		else if(status == Enums.HttpStatus.HTTP404){
			headerStatus = "404 Not Found";
		}
		else if(status == Enums.HttpStatus.HTTP500){
			headerStatus = "500 Internal Server Error";
		}
		else if(status == Enums.HttpStatus.HTTP501){
			headerStatus = "501 Not Implemented";
		}
		header.append(headerStatus);
		header.append(EOF);
		header.append("Connection: close");
		header.append(EOF);
		header.append("Server: JwapServer v1.0");
		header.append(EOF);
		header.append(ConnectionCore.getMimeHeader(path));
		header.append(EOF);
		return header.toString();
	}
	
}
